package blog.util;

import io.vertx.core.Vertx;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.SqlClient;

import java.util.Map;

public class MySQLUtil {

  private static SqlClient mysqlClient;

  public static void connect(Vertx vertx) {
    MySQLConnectOptions mySQLConnectOptions = new MySQLConnectOptions().setPort(3360).setHost("127.0.0.1").setUser("xiaohu").setPassword("xiaohu@MySQL_1121").setDatabase("vertx_blog");
//    MySQLConnectOptions mySQLConnectOptions = new MySQLConnectOptions().setPort(3306).setHost("127.0.0.1").setUser("root").setPassword("huhailong").setDatabase("vertx_blog");
    PoolOptions poolOptions = new PoolOptions().setMaxSize(10);
    mysqlClient = MySQLPool.client(vertx, mySQLConnectOptions, poolOptions);
  }

  public static SqlClient run(Vertx vertx){
    if(mysqlClient == null){
      connect(vertx);
    }
    return mysqlClient;
  }

  /**
   * 生成查询语句
   *
   * @param columns 要查询到列
   */
  public static String select(String tableName, String... columns) {
    StringBuilder selectSQLBuilder = new StringBuilder();
    selectSQLBuilder.append("SELECT ");
    for (int i = 0; i < columns.length; i++) {
      if (i < columns.length - 1) {
        selectSQLBuilder.append(columns[i]).append(",");
      } else {
        selectSQLBuilder.append(columns[i]).append(" ");
      }
    }
    selectSQLBuilder.append("FROM ").append(tableName).append(" ");
    return selectSQLBuilder.toString();
  }

  public static String delete(String tableName, String whereStr) {
    return "DELETE FROM " + tableName + " WHERE " + whereStr;
  }

  public static String insert(String tableName, String... columns) {
    StringBuilder insertSQLBuilder = new StringBuilder();
    insertSQLBuilder.append("INSERT INTO ").append(tableName).append(" (");
    for (int i = 0; i < columns.length; i++) {
      if (i < columns.length - 1) {
        insertSQLBuilder.append(columns[i]).append(",");
      } else {
        insertSQLBuilder.append(columns[i]).append(") VALUES (");
      }
    }
    for (int i = 0; i < columns.length; i++) {
      if (i < columns.length - 1) {
        insertSQLBuilder.append("?").append(",");
      } else {
        insertSQLBuilder.append("?").append(") ");
      }
    }
    return insertSQLBuilder.toString();
  }

  public static String updateById(String tableName, Integer id, String...columnName){
    StringBuilder updateSQLBuilder = new StringBuilder();
    updateSQLBuilder.append("UPDATE ").append(tableName).append(" SET ");
    for(int i=0; i<columnName.length; i++){
      if(i < columnName.length - 1){
        updateSQLBuilder.append(columnName[i]).append("=?").append(", ");
      }else{
        updateSQLBuilder.append(columnName[i]).append("=? WHERE id = ").append(id);
      }
    }
    return updateSQLBuilder.toString();
  }

}
